<template>
  <el-dialog
    width="40%"
    append-to-body 
    top="15vh"
    :title="type == 0 ? '导入入库单': '导入采购计划'"
    :close-on-click-modal="false"
    :visible.sync="show"
  >
    <el-form class="import-ware-housing">
      <el-form-item class="line" label="下载筛选：">
        <el-row class="form-items">
          <el-select
            v-model="downParam.drugType"
            placeholder="药品类型"
            class="form-item"
          >
            <template v-for="item in drugTypes">
              <el-option 
                :key="item.id" 
                :label="item.text" 
                :value="item.id">
              </el-option>
            </template>
          </el-select>
        </el-row>
        <el-row class="tip">必选项，下载前请选择（填写完成后上传，请勿随意修改模板或添加其他药品，否则可能会上传失败）</el-row>
        <el-row class="button">
          <el-button
            @click="onDown"
            type="primary"
          >下载{{ type == 0 ? '入库单':'采购单' }}</el-button>
        </el-row>
      </el-form-item>
      <el-form-item label="上传选择：">
        <el-row class="form-items">
            <el-select 
              v-model="postData.supplierId"
              @change="onChangeSupplier"
              placeholder="供应商"
              :clearable="false"
              class="form-item"
            >
              <template v-for="item in suppliers">
                <el-option 
                  :key="item.id" 
                  :label="item.text" 
                  :value="item.id">
                </el-option>
              </template>
            </el-select>
            <el-select 
              v-if="type == 0"
              v-model="postData.wareHousingType"
              placeholder="入库方式"
              :clearable="false"
              class="form-item"
            >
              <template v-for="item in wareHousingTypes">
                <el-option 
                  :key="item.id" 
                  :label="item.text" 
                  :value="item.id">
                </el-option>
              </template>
            </el-select>
        </el-row>
        <el-row class="tip">必选项，请上传前选择</el-row>
      </el-form-item>
      <el-form-item label="上传文件：">
        <el-upload
          ref="upload"
          class="upload-demo"
          name="file"
          :action="uploadUrl"
          :auto-upload="false"
          :headers="headers"
          :on-success="onSuccess"
          :on-error="onError"
          :before-upload="onBeforeUpload"
          :data="postData"
          drag
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此区域</div>
          <el-button size="small">上传文件</el-button>
          <div class="upload-hint" slot="tip">
            <i class="el-icon-warning-outline"></i>
            文件仅支持xls/xlsx格式的文件
          </div>
        </el-upload>
      </el-form-item>
      <div class="dialog-footer">
        <el-button @click="show = false">关闭</el-button>
        <el-button type="primary" :loading="loading" @click="onSubmit">提交</el-button>
      </div>
    </el-form>
  </el-dialog>
</template>

<script>
import { getSuppliers, outTemplate } from "@/api/storageRoom/drugWareHousing";
import { getToken } from '@/utils/auth';
import { mapGetters } from "vuex";

export default {
  name: "importWareHousing",
  inheritAttrs: false,
  props: {
    // 0-入库, 1-采购计划
    type: {
      type: Number,
      default: 0
    }
  },
  data() {
    let baseUrl = process.env.VUE_APP_BASE_API;
    return {
      headers: {
        Authorization: getToken()
      },
      postData: {
        supplierId: null,
        supplierName: null,
        wareHousingType: 6,
        type: null,
        drugType: null
      },
      downParam: {
        drugType: 7,
        type: null,
      },
      drugTypes: [
        { id: 7, text: "西药及中成药" },
        { id: 1, text: "中药饮片" },
        { id: 2, text: "颗粒剂" }
      ],
      flagList: [
        { id: 0, text: "正常" },
        { id: 1, text: "失效" },
      ],
      stockList: [
        { id: 0, text: "有库存" },
        { id: 1, text: "无库存" },
      ],
      uploadUrl: baseUrl + "/drugWareHousing/inTemplate",
      suppliers: [],
      show: false,
      loading: false,
      pharmacyId: null,
    }
  },
  computed: {
    ...mapGetters(["wareHousingTypes"]),
    downUrl() {
      let baseUrl = process.env.VUE_APP_BASE_API;
      return baseUrl + "/drugWareHousing/outTemplate";
    }
  },
  created() {
    this.$store.dispatch("GetInfo").then(res => {
      this.pharmacyId = res.pharmacyId;
    });
    this._getSuppliers();
  },
  mounted() {
    if(this.type == 1) {
      // 采购计划，入库方式默认采购入库
      this.postData.wareHousingType = 1;
    }
  },
  methods: {
    onSubmit() {
      if(!this.postData.supplierName) {
        this.$message.error("请选择供应商");
        return;
      }
      if(this.$refs.upload.uploadFiles.length === 0) {
        this.$message.error('请选择文件!');
        return;
      }
      if(this.type == 1) {
        this.postData.type = 1;
      } else {
        this.postData.type = 2;
      }
      this.postData.drugType = this.downParam.drugType;
      this.loading = true;
      this.$refs.upload.submit();
    },
    onBeforeUpload(file) {
      let isPic =
        file.type == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
      if (!isPic) {
        this.$message.error('上传文件只能是xls、xlsx格式!');
        this.loading = false;
        return false;
      }
      return isPic;
    },
    onSuccess() {
      this.$notify({
        title: "导入成功",
        type: "success"
      });
      this.loading = false;
      this.$refs.upload.clearFiles();
      this.$emit("success");
      this.show = false;
      this.postData.supplierId = null;
      this.postData.supplierName = null;
      this.postData.wareHousingType = null;
      this.downParam.drugType = null;
      this.downParam.drugName = null;
      this.downParam.drugManufactor = null;
      this.downParam.isStock = null;
      this.downParam.status = null;
    },
    onError(error) {
      console.error(error);
      this.loading = false;
      let msg = '请求失败';
      if(error.message.indexOf("{\"status") === 0) {
        msg = JSON.parse(error.message).message;
      }
      this.$notify({
        title: msg,
        type: 'error'
      });
    },
    onChangeSupplier(supplierId) {
      let suppliers = this.suppliers.filter(item => {
        return item.id === supplierId;
      });

      this.supplierError = false;
      this.postData.supplierName = suppliers[0].text;
    },
    onDown() {
      if(this.type == 1) {
        this.downParam.type = 1;
      } else {
        this.downParam.type = 2;
      }
      outTemplate(this.downParam);
    },
    _getSuppliers() {
      getSuppliers().then(res => {
        res.content.forEach(item => {
          this.suppliers.push({
            id: item.id,
            text: item.supplierName
          });
        });
      });
    },
  }
}
</script>

<style>
.import-ware-housing {
  font-size: 14px;
}

.import-ware-housing .el-form-item {
  margin-left: 15px;
  display: flex;
}

.import-ware-housing .upload-hint {
  color: #ff8432;
  font-size: 14px;
}

.import-ware-housing .dialog-footer {
  text-align: center;
}

.import-ware-housing .el-upload-dragger .el-icon-upload {
  margin: 20px 0 10px;
}

.import-ware-housing .el-upload-dragger .el-button {
  margin-top: 5px;
}

.import-ware-housing .el-link {
  border: 1px solid #DCDFE6;
  background: #fff;
  padding: 0 15px;
  font-size: 12px;
}

.import-ware-housing .label {
  text-align: right;
  line-height: 8px;
  font-size: 13px;
  display: block;
  color: #999;
}

.import-ware-housing .el-row.tip {
  font-size: 12px;
  color: #999;
}

.import-ware-housing .el-row.button {
  margin-top: 10px;
}

.import-ware-housing .el-row.form-items .form-item {
  margin-right: 10px;
  width: 150px;
}

.import-ware-housing .el-form-item.line {
  border-bottom: 1px solid #DEDEDE;
  padding-bottom: 18px;
}
</style>